import path from 'node:path';
import { app } from 'electron';
import common from 'mv-common';
import { isDevelopment } from '../utils';

class AwakeApp {
    #schema = app.getName();
    devArgs: [string, Array<string>] | [] = [];

    public start() {
        this.devArgs = isDevelopment()
            ? [process.execPath, [path.resolve(process.argv[1])]]
            : [];
        this.regisSchema();
    }

    public regisSchema() {
        app.setAsDefaultProtocolClient(
            this.#schema,
            ...(this.devArgs as Array<string>)
        );
        this.listener();
    }

    public removeSchema() {
        app.removeAsDefaultProtocolClient(
            this.#schema,
            ...(this.devArgs as Array<string>)
        );
    }

    public handleArgv(argv: Array<string>) {
        const offset = !isDevelopment() ? 1 : 2;
        const url = argv.find(
            (arg, i) => i >= offset && arg.startsWith(this.#schema)
        );
        if (url) return new URL(url);
    }

    public listener() {
        if (common.getSystemInfo().isWindow) {
            app.on('second-instance', (_, argv) => {
                const url = this.handleArgv(argv);
                console.log('params is:', url?.searchParams);
            });
        } else {
            app.on('open-url', (_, argv) => {
                console.log('url is:', argv);
            });
        }
    }
}

export default new AwakeApp();
